<?php
namespace application\modules\cms\controllers;

use system\core\Controller;
use system\libraries\FormValidation;
use application\modules\cms\models\PagesModel;

class Pages extends Controller
{  
    public function __construct()
    {
        parent::__construct();
    }
    
    public function index() 
    {
        $pagesModel = new PagesModel();
        
        $data['pages'] = $pagesModel->get();

        $this->load->vars($data);
    }
    
    public function add()
    {
        $data = array();
        $pagesModel = new PagesModel();
        
        // Form 1
        $formValidation = new FormValidation();
        
        $formValidation->rules('page', 'Page', 'required|callback_checkPage');
        $formValidation->rules('content', 'Content', 'required|min_length[3]|matches[page]');
        
        if ( isset($_POST['btnAdd']) )
        {
            if ( $formValidation->run() )
            {
                echo 'Form 1 success...';
                $pagesModel->page = $_POST['page'];
                $pagesModel->content = $_POST['content'];
                $pagesModel->insert();
            }
        }
        
        // Form 2
        $formValidation2 = new FormValidation('form2');
        $formValidation2->rules('username', 'Username', 'required');
        
        if ( isset($_POST['btnTest']) )
        {
            if ( $formValidation2->run() )
            {
                echo 'Form 2 success...';
            }
        }
        
        $this->load->vars($data);
    }
    
    /** 
     * Callback for adding a page
     * 
     * This callback checks if the page is 'good'.
     * 
     * @param string $str
     * @return mixed
     */
    public function callback_checkPage( $str )
    {
        if ( 1 == 1 )
        {
            return TRUE;
        }

        return 'Your custom error message for field %s.';
    }
    
    /**
     * Edit a page
     * 
     * @param int $id
     */
    public function edit( $id = NULL )
    {
        if ( ! $id || ! is_numeric($id) )
        {
            throw new \Exception('Invalid parameter given.');
        }
        
        $pagesModel = new PagesModel();
        $data['page'] = $pagesModel->find($id);
        
        if ( isset($_POST['btnEdit']) )
        {
            $pagesModel->content = $_POST['content'];
            $pagesModel->update($id);
            redirect('pages');
        }
        
        $this->load->vars($data);
    }
    
    public function delete( $id = NULL )
    {
        $pagesTable = new PagesModel();

        if ( $id )
        {
            $pagesTable->delete( $id );
        }
        else
        {
            $pagesTable->delete();
        }
        
        redirect('pages');
    }
}

/* End of file Pages.php */
